package com.tianchi.lexiang.background;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import com.tianchi.lexiang.R;
import com.tianchi.lexiang.background.util.HddDataBaseVersion;
import com.tianchi.lexiang.background.util.PublicUtil;
import com.tianchi.lexiang.background.util.SingerAddUtil;
import com.tianchi.lexiang.bean.LeXiangConstants;
import com.tianchi.lexiang.bean.Singer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class LanAddSinger extends Activity implements OnClickListener {
	
	private static final String TAG = "LanAddSinger";
	
	private ImageView singerPhoto;
	
	private TextView lanAddSingerInfo;
	private TextView singerName;
	private TextView singerSpell;
	private TextView singerType;
	private TextView singerArea;
	private TextView singerInfo;
	private TextView copyProgressTxt;
	
	private Button previousBtn;
	private Button nextBtn;
	private Button startAddSingerBtn;
	private Button stopAddSingerBtn;
	private Button backBtn;
	
	private ProgressBar copyProgressBar; 
	
	private PublicUtil publicUtil;
	private SingerAddUtil singerAddUtil;
	
	private List<Singer> singerInfos;
	private Singer singer;
	
	private int totalSingers = 0 ;
	private int currentSinger = 1;
	
	private boolean bool = true;
	boolean checkBoxIsChecked = false;
	private String myChiose = "";
	
	private static final String REPLACE = "repalce";
	private static final String NEXT_SINGER = "nextSong";
	private static final String NULL = "null";
	
	private HashMap<String, String> singerTypeMap = new HashMap<String, String>();
	
	private void setSingerTypeMap(){
		singerTypeMap.put(getString(R.string.male), "STP1");
		singerTypeMap.put(getString(R.string.female), "STP2");
		singerTypeMap.put(getString(R.string.combination), "STP3");
	}

	
	private Handler mHandler = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.d(TAG, "[mHandler].....currentSinger===>" + currentSinger);
			Log.d(TAG, "[mHandler].....totalSingers===>" + totalSingers);
			if(currentSinger <= totalSingers){
				showSingerInfo(currentSinger);
				singer = singerInfos.get(currentSinger - 1);
				singer.type = singerTypeMap.get(singer.type);
				Log.d(TAG, "[mHandler]...singer.type===>" + singer.type);
				boolean bool = singerAddUtil.checkSinger(singer);
				Log.d(TAG, "[mHandler]....bool====>" + bool);
				if(bool){
					if(myChiose != null && !"".equals(myChiose)){
						if(NEXT_SINGER.equals(myChiose)){
							currentSinger ++ ;
							mHandler.sendEmptyMessage(0);
						}else{
							new InsertTask().execute(myChiose);
						}
					}else{
						isExistDialog();
					}
				}else{
					new InsertTask().execute(NULL);
				}
			}else{
				startAddSingerBtn.setEnabled(true);
				backBtn.setEnabled(true);
				previousBtn.setEnabled(true);
				nextBtn.setEnabled(true);
				stopAddSingerBtn.setEnabled(false);
				HddDataBaseVersion.setCurrentHddDataBaseVersion();
			}
			
		}
		
	};
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lan_add_singer);
		initView();
		publicUtil = PublicUtil.getPulibUtil();
		singerAddUtil = SingerAddUtil.getInstece(this);
		setSingerTypeMap();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		singerInfos = publicUtil.getAllSingerInfo(LanAddSongIPSetting.localTemporaryFolder);
		totalSingers = singerInfos.size();
		lanAddSingerInfo.setText(getString(R.string.lan_add_singer_info) + totalSingers + getString(R.string.entries));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		showSingerInfo(currentSinger);
		copyProgressBar.setMax(totalSingers);
		copyProgressBar.setProgress(0);
	}
	
	private void initView(){
		singerPhoto = (ImageView)findViewById(R.id.singer_photo);
		
		lanAddSingerInfo = (TextView)findViewById(R.id.lan_add_singer_info);
		
		singerName = (TextView)findViewById(R.id.singer_name_txt);
		
		singerSpell = (TextView)findViewById(R.id.singer_name_first_spell_txt);
		
		singerType = (TextView)findViewById(R.id.singer_type);
		
		singerArea = (TextView)findViewById(R.id.singer_area);
		
		singerInfo = (TextView)findViewById(R.id.singer_introduction);
		
		copyProgressTxt = (TextView)findViewById(R.id.copy_progress_txt);
		copyProgressTxt.setText(0 + "/" + totalSingers);
		
		previousBtn = (Button)findViewById(R.id.previous);
		previousBtn.setOnClickListener(this);
		
		nextBtn = (Button)findViewById(R.id.next);
		nextBtn.setOnClickListener(this);
		
		copyProgressBar = (ProgressBar)findViewById(R.id.copy_progress_bar);
		
		startAddSingerBtn = (Button)findViewById(R.id.start_add_singer_btn);
		startAddSingerBtn.setOnClickListener(this);
		
		stopAddSingerBtn = (Button)findViewById(R.id.pause_add_singer_btn);
		stopAddSingerBtn.setOnClickListener(this);
		
		backBtn = (Button)findViewById(R.id.back_btn);
		backBtn.setOnClickListener(this);
	}
	
	private void showSingerInfo(int currentSingerNumber){
		Singer singer = singerInfos.get(currentSingerNumber - 1);
		singerPhoto.setImageDrawable(Drawable.createFromPath(singer.photoPath));
		singerName.setText(singer.name);
		singerSpell.setText(singer.firstSpell);
		singerType.setText(singer.type);
		singerArea.setText(singer.area);
		boolean bool = publicUtil.detectionuDisk(LanAddSongIPSetting.localTemporaryFolder + singer.name + ".txt");
		if(bool){
			String singerInformation = singerAddUtil.convertCodeAndGetText(LanAddSongIPSetting.localTemporaryFolder + singer.name + ".txt");
			Log.d(TAG, "[showSingerInfo]....singerInfo==>" + singerInfo);
			singerInfo.setText(singerInformation.trim());
			singer.information = singerInformation.trim();
		}else{
			singerInfo.setText(getString(R.string.unknown));
			singer.information = getString(R.string.unknown);
		}
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.previous:
			previousSinger();
			break;
		case R.id.next:
			nextSinger();
			break;
		case R.id.start_add_singer_btn:
			bool = true;
			startAddSingerBtn.setEnabled(false);
			backBtn.setEnabled(false);
			previousBtn.setEnabled(false);
			nextBtn.setEnabled(false);
			stopAddSingerBtn.setEnabled(true);
			mHandler.sendEmptyMessage(0);
			break;
		case R.id.pause_add_singer_btn:
			startAddSingerBtn.setEnabled(true);
			backBtn.setEnabled(true);
			previousBtn.setEnabled(true);
			nextBtn.setEnabled(true);
			stopAddSingerBtn.setEnabled(false);
			bool = false;
			break;
		case R.id.back_btn:
			publicUtil.deleteFolder(LanAddSongIPSetting.localTemporaryFolder);
			LanAddSinger.this.finish();
			break;

		default:
			break;
		}
	}
	
	private void previousSinger(){
		if (currentSinger > 1) {
			Log.d(TAG, "[previousSinger]....currentSinger===>" + currentSinger);
			currentSinger--;
			showSingerInfo(currentSinger);
		}
		
	}
	
	private void nextSinger(){
		if (currentSinger < totalSingers) {
			Log.d(TAG, "[previousSinger]....currentSinger===>" + currentSinger);
			currentSinger++;
			showSingerInfo(currentSinger);
		}
	}
	
	private class InsertTask extends AsyncTask<String, Integer, Boolean>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			boolean boolea = false;
			if(REPLACE.equals(params[0])){
				String localPath =  LeXiangConstants.SIGER_HARD_DISK_PATH + singer.name + "(new)" + ".jpg";
				Log.d(TAG, "[InsertTask].....localPath===>" + localPath);
				boolean bool = publicUtil.copyInfo(singer.photoPath,localPath);
				Log.d(TAG, "[InsertTask]...bool===>" + bool);
				if(bool){
					File file = new File(localPath);
					if(file.exists()){
						localPath = LeXiangConstants.SIGER_HARD_DISK_PATH + singer.name + ".jpg";
						Log.d(TAG, "[InsertTask]....localPath===>"  + localPath);
						file.renameTo(new File(localPath));
						boolean isSuccess = singerAddUtil.updateSingerInfo(singer);
						Log.d(TAG, "[InsertTask]....isSuccess===>"  + isSuccess);
						if(isSuccess)
							boolea = true;
					}
				}
			}else{
				String localPath =  LeXiangConstants.SIGER_HARD_DISK_PATH + singer.name + ".jpg";
				Log.d(TAG, "[InsertTask].....localPath===>" + localPath);
				boolean bool = publicUtil.copyInfo(singer.photoPath,localPath);
				Log.d(TAG, "[InsertTask].....bool===>" + bool);
				if(bool){
					boolean isSuccess = singerAddUtil.insertSinger(singer);
					Log.d(TAG, "[InsertTask]....isSuccess===>"  + isSuccess);
					if(isSuccess)
						bool = true;
				}
			}
			publishProgress(currentSinger);
			return boolea;
			
		}
		
		@Override
		protected void onProgressUpdate(Integer... params) {
			super.onProgressUpdate(params);
			Log.d(TAG, "[InsertTask].....params[0]===>" + params[0]);
			copyProgressBar.setProgress(params[0]);
			copyProgressTxt.setText(params[0] + "/" + totalSingers);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(!result){
				Toast.makeText(LanAddSinger.this, getString(R.string.current_add_singer_failure), Toast.LENGTH_SHORT);
			}
			if(bool){
				Log.d(TAG, "[InsertTask].....currentSinger===>" + currentSinger);
				currentSinger ++;
				mHandler.sendEmptyMessage(0);
			}
		}
	}
	
	protected void isExistDialog() {

		AlertDialog.Builder builder = new Builder(LanAddSinger.this);
		builder.setIcon(android.R.drawable.ic_menu_help);
		builder.setTitle(getString(R.string.whether_to_replace));
		builder.setMultiChoiceItems(
				new String[] { getString(R.string.remember_my_choice) },
				new boolean[] { false },
				new DialogInterface.OnMultiChoiceClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which,
							boolean isChecked) {
						checkBoxIsChecked = isChecked;
					}
				});
		builder.setPositiveButton(getString(R.string.repalce),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (checkBoxIsChecked) {
							myChiose = REPLACE;
						}
						new InsertTask().execute(REPLACE);
						dialog.dismiss();
					}
				});

		builder.setNegativeButton(getString(R.string.next_singer),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (checkBoxIsChecked) {
							myChiose = NEXT_SINGER;
						}
						currentSinger ++;
						mHandler.sendEmptyMessage(0);
						dialog.dismiss();
					}
				});
		builder.create().show();
	}


}
